import { reactive, nextTick, onActivated } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { IAnyKeyObject } from '@/types/common'
import { queryModuleDetail } from '@/apis/Module'

export function ListCommon($router: any, $store: any, instance: any, operatorType?: String) {
  const datas = reactive<IAnyKeyObject>({
    amid: '', // 区域ID（模块ID）
    //acceptMold (验收类型)： softReview 软装复查/ softCheck 软装验收 / hardReview 硬装复查 / hardCheck 硬装验收
    acceptMold: '',
    detail: {
      // 区域详情
      acceptID: '',
      amid: '', // 区域ID（模块ID）
      module1: '',
      module2: '',
      facades: [] // 立面列表
    },
    list: [],
    formData: {
      caid: '', //验收id
      amid: '', // 验收区域ID
      facade: '' //立面数量
    },
    submitOver: false
  })

  const onFacadeDetail = (sfid: any) => {
    $router.push({
      path: '/facade/fileList',
      query: {
        sfid,
        acceptMold: datas.acceptMold,
        type: operatorType
      }
    })
  }
  const onFacadeAll = () => {
    $router.push({
      path: '/facade/allFile',
      query: {
        amid: datas.amid,
        acceptMold: datas.acceptMold,
        type: operatorType
      }
    })
  }

  const getDetailData = () => {
    queryModuleDetail(datas.amid).then((res) => {
      const d = res.data || {}
      const list = d?.facades || []
      datas.detail = d
      datas.list = list.sort((a: any, b: any) => {
        return a.sortNumber - b.sortNumber
      })
      if (operatorType === 'edit') {
        datas.formData = {
          caid: d.acceptID,
          amid: d.amid,
          facade: datas.list.length
        }
        if (datas.list.length > 0) {
          datas.submitOver = true
        }
      }
    })
  }

  onActivated(() => {
    nextTick(() => {
      getDetailData()
    })
  })

  onBeforeRouteLeave((to, from, next) => {
    const instanceName = instance?.type?.name
    const toName: any = to.name
    if (['FacadeAllFile', 'FacadeFileList'].includes(toName)) {
      $store.commit('routerKeep/removeCache', instanceName)
    } else {
      $store.commit('routerKeep/resetCache', instanceName)
    }
    next()
  })

  return {
    datas,
    getDetailData,
    onFacadeAll,
    onFacadeDetail
  }
}
